<?php
App::uses('AppController', 'Controller');
/**
 * Menuses Controller
 *
 * @property Menus $Menus
 */
class MenusesController extends AppController {
	public $helpers = array('FileUpload.FileUpload');
	public $components = array('FileUpload.FileUpload');

	public function beforeFilter(){
		parent::beforeFilter();
		$this->FileUpload->uploadDir('files'.DS.'upload'.DS.'images');
	}
	
/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->Menus->recursive = 0;
		$this->set('menuses', $this->paginate());
	}

/**
 * view method
 *
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		$this->Menus->id = $id;
		if (!$this->Menus->exists()) {
			throw new NotFoundException(__('Invalid menus'));
		}
		$this->set('menus', $this->Menus->read(null, $id));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
// 			debug($this->request->data); die;
			$this->request->data['Menus']['slug'] = strtolower(Inflector::slug($this->request->data['Menus']['name'],'-'));
			if($this->FileUpload->success){
				$this->request->data['Menus']['upload_id'] = $this->Menus->Upload->getLastInsertID();
			}else{
				// 				throw new NotFoundException($this->FileUpload->showErrors());
			}
				
			
			$this->Menus->create();
			if ($this->Menus->save($this->request->data)) {
				$this->Session->setFlash(__('The menus has been saved'));
				
				if($this->request->data['Menus']['parent_id'] == null || $this->request->data['Menus']['parent_id'] == ''){
					$this->loadModel('Configuration');
					$data['Configuration']['name'] = $this->request->data['Menus']['slug'];
					$data['Configuration']['cfg_group_id'] = 5;
					$data['Configuration']['domain_id'] = $this->request->data['Domain']['Domain'][0];
					$data['Configuration']['value'] = 'null';
					$this->Configuration->create();
					if($this->Configuration->save($data)){
// 						debug($data); die;
					}else{
						throw new NotFoundException(__('Invalid Configuration for menu'));
					}
				}
				
				if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'menus'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The menus could not be saved. Please, try again.'));
			}
		}
		
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
			// dodajemy do domeny
			$this->Menus->Domain->id = $this->passedArgs['d'];
			if ($this->Menus->Domain->exists()) {
				$data['Domain']['Domain'][0] = $this->passedArgs['d'];
				$this->request->data = $data;
			}
		}
		
		if(isset($this->passedArgs['pi']) && !empty($this->passedArgs['pi'])){
			// dodajemy do domeny
			$this->Menus->id = $this->passedArgs['pi'];
			if ($this->Menus->exists()) {
				$data['Menus']['parent_id'] = $this->passedArgs['pi'];
				$this->request->data = $data;
			}
		}
		
		$domains = $this->Menus->Domain->find('list');
		
		$options['joins'] = array(
		    array('table' => 'domains_menuses',
		        'alias' => 'DomainsMenus',
		        'type' => 'inner',
		        'conditions' => array(
		            'Menus.id = DomainsMenus.menus_id'
		        )
		    ),
		    array('table' => 'domains',
		        'alias' => 'Domain',
		        'type' => 'inner',
		        'conditions' => array(
		            'DomainsMenus.domain_id = Domain.id'
		        )
		    )
		);
		$options['conditions'] = array(
		    'Domain.id' => $this->passedArgs['d']
		);
		
		$parentMenuses = $this->Menus->find('threaded',$options);
		$parentMenuses = $this->treeForCombobox($parentMenuses,'Menus',array('model'=>'Menus','name'=>'name'),false);
		
		$menu_positions = Configure::read('Config.menu_positions');
		
		//$submenus = $this->Menus->Submenu->find('list');
		$this->set(compact('parentMenuses', 'domains','menu_positions'));
	}

/**
 * edit method
 *
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		$this->Menus->id = $id;
		if (!$this->Menus->exists()) {
			throw new NotFoundException(__('Invalid menus'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if($this->FileUpload->success){
				$this->request->data['Menus']['upload_id'] = $this->Menus->Upload->getLastInsertID();
			}else{
// 				throw new NotFoundException($this->FileUpload->showErrors());
			}
			
			if(!isset($this->request->data['Menus']['slug']) || empty($this->request->data['Menus']['slug'])) 
				$this->request->data['Menus']['slug'] = strtolower(Inflector::slug($this->request->data['Menus']['name'],'-'));
			if ($this->Menus->save($this->request->data)) {
				$this->Session->setFlash(__('The menus has been saved'));
					


// 				debug($this->request->data); die;
				if(isset($this->request->data['Article']['Article']) && !empty($this->request->data['Article']['Article'])){
					$this->loadModel('Article');
					$menus_id = (int)$this->request->data['Menus']['id'];
					if($this->Article->updateAll(array('Article.menuses_id'=>$menus_id),array('Article.id'=>$this->request->data['Article']['Article']))){
						
					}
				}
				
				if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'menus'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The menus could not be saved. Please, try again.'));
			}
		} else {
			$this->request->data = $this->Menus->read(null, $id);
		}
		
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
			// dodajemy do domeny
			$this->Menus->Domain->id = $this->passedArgs['d'];
			if ($this->Menus->Domain->exists()) {
				$this->request->data['Domain']['domain_id'] = $this->passedArgs['d'];
			}
		}
		
		$options['joins'] = array(
		    array('table' => 'domains_menuses',
		        'alias' => 'DomainsMenus',
		        'type' => 'inner',
		        'conditions' => array(
		            'Menus.id = DomainsMenus.menus_id'
		        )
		    ),
		    array('table' => 'domains',
		        'alias' => 'Domain',
		        'type' => 'inner',
		        'conditions' => array(
		            'DomainsMenus.domain_id = Domain.id'
		        )
		    )
		);
		$options['conditions'] = array(
		    'Domain.id' => $this->passedArgs['d']
		);
		
		$parentMenuses = $this->Menus->find('threaded',$options);
		$parentMenuses = $this->treeForCombobox($parentMenuses,'Menus',array('model'=>'Menus','name'=>'name'),false);
		
		$domains = $this->Menus->Domain->find('list');
		$this->loadModel('Article');
		$options = array();
		$options['conditions'] = array(
				'Article.domain_id' => $this->passedArgs['d']
		);
		$articles = $this->Article->find('list',$options);
		
		$options = array();
		$options['conditions'] = array(
				'Article.domain_id' => $this->passedArgs['d'],
				'Article.menuses_id' => $id,
		);
		$options['fields'] = array('Article.id');
		$articles_selected = $this->Article->find('list',$options);
		$menu_positions = Configure::read('Config.menu_positions');
		
		$this->set(compact('parentMenuses', 'domains','menu_positions','articles','articles_selected'));
	}

/**
 * delete method
 *
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Menus->id = $id;
		if (!$this->Menus->exists()) {
			throw new NotFoundException(__('Invalid menus'));
		}
		if ($this->Menus->delete()) {
			$this->Session->setFlash(__('Menus deleted'));
			if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'menus'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Menus was not deleted'));
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'menus'));
		$this->redirect(array('action' => 'index'));
	}
	

/**
 * 
 * Move up menu position
 * @param unknown_type $id
 * @param unknown_type $delta
 */	
	function up($id = null, $delta = null){
		$this->autoRender = false;
		
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Menus->id = $id;
		if (!$this->Menus->exists()) {
			throw new NotFoundException(__('Invalid menus'));
		}

		if ($delta > 0) {
			$return = $this->Menus->moveUp($this->Menus->id, abs($delta));
		} else {
			$this->Session->setFlash('Please provide a number of positions the category should be moved up.');
		}
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'menus'));
		$this->redirect(array('action' => 'index'), null, true);
	
	}
	
	function down($id = null, $delta = null) {
		$this->autoRender = false;
		
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Menus->id = $id;
		if (!$this->Menus->exists()) {
			throw new NotFoundException(__('Invalid menus'));
		}
	
		if ($delta > 0) {
			$this->Menus->moveDown($this->Menus->id, abs($delta));
		} else {
			$this->Session->setFlash('Please provide the number of positions the field should be moved down.');
		}
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'menus'));
		$this->redirect(array('action' => 'index'), null, true);
	}
	
	function reorder() {
		$this->Menus->reorder();
		$this->redirect(array('action' => 'index'), null, true);
	}
}
